<template>
  <div>
    <van-nav-bar
      title="修改密码"
      left-text="返回"
      left-arrow
      fixed
      @click.left.native="$router.go(-1)"
    ></van-nav-bar>
    <van-cell-group class="pwd">
      <van-field
        v-model="oldpwd"
        required
        :error-message="oldpwdState"
        label="原密码"
        placeholder="请输入原密码"
        size="large"
        @blur="checkPwd"
      />
      <van-field
        v-model="newpwd"
        required
        :error-message="newpwdState"
        label="新密码"
        placeholder="请输入新密码(6位数字)"
        size="large"
        @blur="checknewPwd"
      />
      <van-field
        v-model="repwd"
        required
        :error-message="repwdState"
        label="确认新密码"
        placeholder="请确认新密码"
        size="large"
        @blur="checkrePwd"
      />
    </van-cell-group>
    <van-button type="primary" @click="updatePwd" class="btn" size="large"
      >确认修改</van-button
    >
  </div>
</template>

<script>
import { mapState } from "vuex"
export default {
  computed: {
    ...mapState(["user"]),
  },
  data() {
    return {
      oldpwd: "",
      newpwd: "",
      repwd: "",
      oldpwdState: "",
      newpwdState: "",
      repwdState: "",
    }
  },
  methods: {
    checkPwd() {
      let exp = /^\d{6}$/
      if (exp.test(this.oldpwd)) {
        this.oldpwdState = ""
        return true
      } else {
        this.oldpwdState = "密码应为6位数字"
        return false
      }
    },
    checknewPwd() {
      let exp = /^\d{6}$/
      if (exp.test(this.newpwd)) {
        this.newpwdState = ""
        return true
      } else {
        this.newpwdState = "密码应为6位数字"
        return false
      }
    },
    checkrePwd() {
      let exp = /^\d{6}$/
      if (exp.test(this.repwd) && this.repwd == this.newpwd) {
        this.repwdState = ""
        return true
      } else {
        this.repwdState = "密码应为6位数字且与新密码相同"
        return false
      }
    },
    updatePwd() {
      if (this.checkPwd() && this.checknewPwd() && this.checkrePwd()) {
        console.log("验证成功,开始修改密码")
        const url = "user/editpwd"
        const params = `unames=${this.user.data.unames}&oldpwd=${this.oldpwd}&newpwd=${this.newpwd}`
        this.axios.post(url, params).then(res => {
          console.log(res)
          if (res.data.code == 1) {
            this.$dialog.alert({
              title: "修改密码成功",
              message: "请用新密码登录",
            })
            this.$router.push("/login")
          } else {
            this.$dialog.alert({
              message: "修改密码失败,请重试",
            })
          }
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.pwd {
  margin-top: 14vw;
}
.btn {
  display: block;
  margin: 5vw 0;
}
</style>
